<template>

    <footer class="ui-c-f">
        <div class="ui-price price ui-v-a"><span>{{!selectedSpecValue.selectedSku[0]?0:selectedSpecValue.selectedSku[0].price/10}}</span>
        </div>
        <button :class="['ui-btn-yellow', 'ui-v-a',canNext?'':'un']" @click="next">
            <span>{{skuSelectShow?'确定':'加入购物车'}}</span>
        </button>
    </footer>

    <div class="float-layer" v-if="skuSelectShow">
        <div class="float-shade" @click="close"></div>
        <div class="float-body">

            <div class="productArea" v-if="finishSelect">
                <div>
                    <div class="tumb-cover">
                        <img :src="selectedSpecValue.selectedSku[0].pic[0]+'?imageView2/1/w/200/h/200'">
                    </div>
                    <div class="right-part">
                        <div class="tumb-top ui-c-f">
                            <div class="thum-price">
                                <div class="ui-price price-red">{{selectedSpecValue.selectedSku[0].price/10}}</div>
                                <div v-if="selectedSpecValue.selectedSku[0].price_cost>0" class="ui-price price-gray">
                                    {{selectedSpecValue.selectedSku[0].price_cost/10}}
                                </div>
                            </div>
                            <h1>
                                {{selectedSpecValue.selectedSku[0].title}}
                            </h1>
                            <div v-if="selectedSpecValue.selectedSku[0].label&&selectedSpecValue.selectedSku[0].label.length>0"
                                 class="tags">
                                <span v-for="val of label" class="tag">{{val}}</span>
                            </div>
                            <div class="stock">
                                库存:{{selectedSpecValue.selectedSku[0].stock}}件
                            </div>
                        </div>
                        <div class="ui-counter ui-c-f">
                            <div class="ui-decs ui-v-a" @click="changeNumber(-1)"></div>
                            <input type="tel" maxlength="2" class="quantity" v-model="quantity">

                            <div class="ui-add ui-v-a" @click="changeNumber(1)"></div>
                        </div>


                    </div>
                </div>
            </div>

            <div class="categoryArea">

                <template v-for="(spec_id,spec) of specs">

                    <div class="category-title">
                        {{spec.name}}
                    </div>

                    <template v-if="strategy[spec_id]">
                        <span v-for="(main_spec_name, sub_specs) of strategy[spec_id] "
                              @click="selectSubTag(spec_id,main_spec_name)"
                              :class="['category-tag', strategySelected.main_spec_name==main_spec_name?'select':'']">{{main_spec_name}}</span>

                        <div v-if="strategySelected.main_spec_name" class="category-strategy">
                            <div class="category-subtitle"></div>
                            <span v-for="(spec_value_id,spec_value_name) of strategy[spec_id][strategySelected.main_spec_name] "
                                  :class="['category-tag', strategySelected.spec_value_id==spec_value_id?'select':'']"
                                  @click="selectSubTag(spec_id,strategySelected.main_spec_name,spec_value_id)">{{spec_value_name}}</span>
                        </div>
                    </template>


                    <template v-else>
                    <span v-for="(val_id,val) of spec.values"
                          :class="['category-tag',canSelect(spec_id, val_id)?'':'un',isSelected(spec_id, val_id)?'select':'']"
                          @click="selectTag(spec_id, val_id)">{{val.name}}</span>

                    </template>
                </template>
            </div>

            <div class="ui-page-holder"></div>
        </div>
    </div>
</template>

<script type="text/babel">
    import Vue from 'vue'
    import array from '../libs/array'
    import http from '../libs/http'

    export default{
        props: ['selectedSku', 'relative', 'skus', 'strategy'],
        data(){
            return {
                skuSelectShow: false,


                strategySelected: {
                    main_spec_name: '',
                    spec_value_id: ''
                },

                quantity: 1,

                selectedSpecValue: {
                    selectedSku: []
                },
                /**
                 *  {
                 *      spec_id:
                 *      {
                 *          spec_value_id:
                 *          skus:[]
                 *      }
                 *  }
                 *
                 */

                specs: {},
                /**
                 *  spec_id:{
                 *      name: 颜色
                 *      values:{
                 *          spec_value_id:{
                 *              name: 红色,
                 *              skus:[{
                 *
                 *              }]
                 *          }
                 *      }
                 *  }
                 *
                 *
                 */
                inited: false
            };
        },
        computed: {
            finishSelect: function () {
                return this.selectedSpecValue.selectedSku.length == 1;
            },

            canPay: function () {
                if (!this.finishSelect) //没选完
                    return;

                return this.quantity <= this.selectedSpecValue.selectedSku[0].stock;
            },

            canNext: function () {
                if (!this.skuSelectShow) {
                    if (!this.canPay && this.skus.length == 1) {
                        return false
                    }
                } else {
                    return this.canPay
                }

                return true;
            }
        },

        watch: {
            selectedSku: function () {
                if (!this.inited) {
                    this.inited = true;
                    this.init();
                }
            },
        },

        methods: {

            init: function () {
                var self = this;
                var specs = {};
                var tmpSpec;

                self.skus.push(self.selectedSku);

                self.relative.forEach(function (spec) {
                    tmpSpec = {
                        name: spec.name,
                        values: {}
                    };
                    specs[spec._id] = tmpSpec;


                    self.skus.forEach(function (sku) {

                        sku.specs.some(function (sku_spec) {
                            if (spec._id == sku_spec.spec_id) {

                                if (!tmpSpec.values[sku_spec.specvalue_id])
                                    tmpSpec.values[sku_spec.specvalue_id] = {
                                        name: sku_spec.specvalue_name,
                                        skus: []
                                    };

                                tmpSpec.values[sku_spec.specvalue_id].skus.push(sku);
                                return true;
                            }
                        });

                    })
                });

                self.specs = specs;

                self.selectedSpecValue.selectedSku.push(self.selectedSku);


                self.selectedSku.specs && self.selectedSku.specs.forEach(function (spec) {

                    if (self.strategy[spec.spec_id])
                        self.selectSubTag(spec.spec_id, null, spec.specvalue_id);
                    else
                        self.selectTag(spec.spec_id, spec.specvalue_id);
                })
            },

            changeSku: function () {
                this.close();
                this.$dispatch('change-sku');
            },
            close: function () {
                this.skuSelectShow = false;
            },
            next: function () {
                var self = this;

                if (!self.canNext) {
                    return;
                }

                if (self.skuSelectShow) {
                    if (!self.finishSelect)
                        return;

                    http.post({
                        url: api + 'cart/add',
                        jsonp: true,
                        data: {
                            sku_id: self.selectedSpecValue.selectedSku[0]._id,
                            quantity: self.quantity
                        }

                    }).then(function (obj) {
                        if (obj.code == 0) {
                            self.$dispatch('toast', '添加成功');
                            self.$dispatch('add-cart', obj.data.count);
                            self.close();
                        } else if (obj.msg) {
                            self.$dispatch('toast', obj.msg);
                        }
                    })

                } else
                    self.skuSelectShow = true;
            },

            //如果没选中，那么是否可被选
            canSelect: function (spec_id, spec_value_id) {

                for (var i in this.selectedSpecValue.selectedSku) {
                    if (this.selectedSpecValue.selectedSku[i]._id == spec_value_id)
                        return sku.stock > 0;
                }

                return false;
            },


            //是否已经选中
            isSelected: function (spec_id, spec_value_id) {
                if (!this.selectedSpecValue[spec_id]) //没选
                    return;

                return this.selectedSpecValue[spec_id].spec_value_id == spec_value_id; //选并且相同
            },

            //点选，判是取消还是选中
            selectTag: function (spec_id, spec_value_id) {
                var self = this;

                if (this.selectedSpecValue[spec_id]) { //选过这个spec且已选中本value

                    var isDelete = this.selectedSpecValue[spec_id].spec_value_id == spec_value_id;

                    if (isDelete)
                        return;
                    // Vue.delete(this.selectedSpecValue, spec_id);
                    else
                        Vue.set(this.selectedSpecValue, spec_id, {
                            spec_value_id: spec_value_id,
                        });

                    //重新算交集
                    var res = this.skus;

                    self.relative.forEach(function (spec) {

                        if (self.selectedSpecValue[spec._id]) {

                            res = array.intersection(res, self.getSkusBySpec(spec._id, self.selectedSpecValue[spec._id].spec_value_id), function (a, b) {
                                return a._id == b._id;
                            });
                        }
                    });

                    this.selectedSpecValue.selectedSku = res;
                } else {
                    this.selectedSpecValue.selectedSku = array.intersection(this.selectedSpecValue.selectedSku, this.getSkusBySpec(spec_id, spec_value_id), function (a, b) {
                        return a._id == b._id;
                    });

                    Vue.set(this.selectedSpecValue, spec_id, {
                        spec_value_id: spec_value_id,
                    });
                }
            },

            getSkusBySpec: function (spec_id, spec_value_id) {

                var skus = [], key, spec;
                for (key in this.specs) {
                    spec = this.specs[key];

                    if (key == spec_id) {
                        if (!spec_value_id) {
                            for (var tmpKey in spec.values) {
                                skus.push();
                            }
                        } else {
                            skus = spec.values[spec_value_id].skus;
                            break;
                        }
                    }
                }

                return skus;
            },

            changeNumber: function (count) {
                var quan = this.quantity + count;
                if (quan > this.selectedSpecValue.selectedSku[0].stock || quan < 1)
                    return;
                this.quantity = quan;
            },

            selectSubTag: function (spec_id, main_spec_name, spec_value_id) {
                if (!main_spec_name && !spec_value_id)
                    return;

                if (!main_spec_name) { //初始化时使用

                    for (var tmp_main_spec_name in this.strategy[spec_id]) {
                        if (main_spec_name)
                            break;

                        for (var key in this.strategy[spec_id][tmp_main_spec_name]) {
                            if (spec_value_id == key) {
                                main_spec_name = tmp_main_spec_name;
                                break;
                            }
                        }
                    }

                } else if (!spec_value_id) { //选中主spec默认选中第一个subSpec时使用
                    for (var key in this.strategy[spec_id][main_spec_name]) {
                        spec_value_id = key;
                        break
                    }
                }
//                console.log(spec_id, main_spec_name, spec_value_id);

                this.strategySelected.main_spec_name = main_spec_name;
                this.strategySelected.spec_value_id = spec_value_id;


                this.selectTag(spec_id, spec_value_id);
            }

        }
    }
</script>

<style scoped>
    .right-part {
        padding: 8px 0;
        margin-left: 116px;
        height: 100px;
    }

    .ui-counter {
        position: absolute;
        right: 8px;
    }

    .clearAll {
        float: right;
        font-size: 12px;
    }

    .categoryArea {
        padding: 24px;

    }

    .category-title {
        font-size: 12px;
        color: #888888;
        border-bottom: solid 1px #dddddd;
        width: 120px;
        margin-bottom: 8px;
        margin-top: 16px;
    }

    .category-subtitle::before {
        content: '';
        display: block;
        position: absolute;
        width: 8px;
        height: 8px;
        background: url(../../static/img/ic_arrow_111up.png) #f0f0f0 no-repeat center;
        background-size: contain;
        opacity: 1;
        margin-top: -5px;
        margin-left: 8px;
    }

    .category-subtitle {
        font-size: 12px;
        color: #888888;
        border-bottom: solid 1px #aaaaaa;
        margin-right: 200px;
        margin-bottom: 4px;
    }

    .category-tag {
        padding: 8px;
        font-size: 12px;
        text-align: center;
        min-width: 16px;
        height: 16px;
        background: #dddddd;
        display: inline-block;
        margin-right: 8px;
        margin-bottom: 8px;
        transition: all 0.3s;
        -webkit-transition: all 0.3s;
    }

    .tag:first-child {
        padding: 2px;
        font-size: 10px;
        color: white;
        background: #ffba00;
    }

    .tag {
        padding: 2px;
        font-size: 10px;
        color: #888888;
        background: #eeeeee;
    }

    .quantity {
        width: 28px;
        height: 28px;
        text-align: center;
        border: solid 1px #ddd;
        float: left;
        border-top: none;
        border-bottom: none;
        line-height: 28px;
    }

    .price-red {
        color: #ff0000;
        font-size: 14px;
        font-weight: normal;
        display: inline-block;
    }

    .price-gray {
        display: inline-block;
        color: #888888;
        text-decoration: line-through;
        font-size: 11px;
    }

    .stock {
        font-size: 10px;
        color: #888888;
    }

    .category-tag.un {
        color: #aaaaaa;
        background: #E8E8E8;
    }

    .category-tag.select {
        background: #111111;
        color: white;
    }

    h1 {
        font-size: 13px;
        font-weight: lighter;
        margin-right: 80px;
    }

    .tag:first-child {
        padding: 2px;
        font-size: 10px;
        color: white;
        background: #ffba00;
    }

    .tag {
        padding: 2px;
        font-size: 10px;
        color: #888888;
        background: #eeeeee;
    }

    .float-layer {
        width: 100%;
        height: 100%;
        bottom: 0;
        left: 0;
        position: fixed;
        z-index: 10;
    }

    .float-shade {
        width: 100%;
        height: 150%;
        bottom: 0;
        left: 0;
        position: fixed;
        z-index: 10;
        background: rgba(0, 0, 0, 0.4);
        opacity: 1;
        transition: opacity 0.3s;
        -webkit-transition: opacity 0.3s;
    }

    .float-body {
        bottom: 0;
        position: fixed;
        z-index: 11;
        left: 0;
        width: 100%;
        background: #f0f0f0;
        transition: bottom 0.3s;
        -webkit-transition: bottom 0.3s;
    }

    .productArea {
        background: white;
    }

    .tumb-cover {
        margin: 8px;
        width: 100px;
        height: 100px;
        position: absolute;
    }

    .tumb-cover > img {
        width: 100%;
        height: 100%;
    }

    .tumb-top {
        height: 70px;
    }

    .thum-price {
        float: right;
        margin-right: 8px;
        text-align: right;
    }

    .thum-price > * {
        display: block !important;
    }

    .thum-bottom .stock {
        padding: 2px 0;
    }

    footer .ui-price {
        color: #f9e043;
        font-size: 13px;
        height: 100%;
        float: left;
        margin: 0 5px;
    }

    footer .ui-btn-yellow {
        float: right;
        padding: 0;
        height: 34px;
        margin: 5px;
    }

    .ui-btn-yellow.un {
        background: #dddddd;
        color: #888888;
    }

</style>